package cn.zsc.netdisk.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ccyingO
 * @date 2021/2/4
 */
public class EncodeUtil {
    private final static String[] HEX_DIGITS = { "0", "1", "2", "3", "4",
            "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" };
    private final static int M = 256;

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) { n += M; }
        int d1 = n >> 4;
        int d2 = n & 0xf;
        return HEX_DIGITS[d1] + HEX_DIGITS[d2];
    }

    /**
     * 转换字节数组为16进制字串
     * @param bytes 字节数组
     * @return 16进制字串
     */
    private static String byteArrayToHexString(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(byteToHexString(b));
        }
        return result.toString();
    }

    /**
     * Base64+MD5摘要算法加密
     * @param origin 要进行加密字符串
     * @return 加密后字符串
     * */
    public static String encode(String origin) {
        String result = null;
        try {
            result = Base64.getEncoder().encodeToString(origin.getBytes());
            MessageDigest md = MessageDigest.getInstance("MD5");
            result = byteArrayToHexString(md.digest(result.getBytes()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }
}
